import 'package:flutter/material.dart';
import 'package:get/get.dart';

import '../constants/enums/app_status.dart';
import '../services/analytics_service.dart';

/// 应用控制器
/// 负责管理全局应用状态
class AppController extends GetxController {
  // 单例访问器
  static AppController get to => Get.find();
  
  // 注入服务
  final AnalyticsService _analyticsService = Get.find<AnalyticsService>();
  
  // 应用状态
  final Rx<AppStatus> _appStatus = AppStatus.initial.obs;
  AppStatus get appStatus => _appStatus.value;
  set appStatus(AppStatus value) => _appStatus.value = value;
  
  // 是否是首次启动
  final RxBool _isFirstLaunch = true.obs;
  bool get isFirstLaunch => _isFirstLaunch.value;
  set isFirstLaunch(bool value) => _isFirstLaunch.value = value;
  
  // 是否已完成初始化
  final RxBool _isInitialized = false.obs;
  bool get isInitialized => _isInitialized.value;
  
  // 应用版本
  final RxString _appVersion = ''.obs;
  String get appVersion => _appVersion.value;
  
  // 是否显示开发者模式
  final RxBool _showDeveloperMode = false.obs;
  bool get showDeveloperMode => _showDeveloperMode.value;
  set showDeveloperMode(bool value) => _showDeveloperMode.value = value;
  
  @override
  void onInit() {
    super.onInit();
    
    // 初始化应用状态
    _initializeApp();
  }
  
  /// 初始化应用
  Future<void> _initializeApp() async {
    try {
      _appStatus.value = AppStatus.initializing;
      
      // 模拟初始化过程
      await Future.delayed(const Duration(seconds: 2));
      
      // 获取应用版本
      _appVersion.value = '1.0.0';
      
      // 设置为已初始化
      _isInitialized.value = true;
      _appStatus.value = AppStatus.success;
      
      // 记录分析事件
      _analyticsService.logEvent('app_initialized');
    } catch (e) {
      _appStatus.value = AppStatus.error;
      debugPrint('初始化应用时出错: $e');
    }
  }
  
  /// 重启应用初始化
  Future<void> restartInitialization() async {
    _isInitialized.value = false;
    await _initializeApp();
  }
  
  /// 切换开发者模式
  void toggleDeveloperMode() {
    _showDeveloperMode.value = !_showDeveloperMode.value;
  }
} 